/*
 * @Author: chengsl
 * @Date: 2023-05-09 18:04:53
 * @LastEditors: chengsl
 * @LastEditTime: 2023-05-10 16:05:37
 * @Description: file content
 */
import { constantRouterMap } from '@/router/routers'
import Layout from '@/layout/index'

const permission = {
  state: {
    routers: constantRouterMap, // 项目所有路由，包括异步加载和固定路由
    addRouters: [], // 所有异步加载的的路由
    siderbarMenuList: [], // 左侧菜单列表
    sidebarRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    /* 设置侧边栏的路由 */
    SET_SIDEBAR_ROUTERS: (state, routers) => {
      state.sidebarRouters = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, asyncRouter) {
      commit('SET_ROUTERS', asyncRouter)
    }
  },
  /**
   * @description: 添加侧边栏路由
   * @param {*} sidebarRouter
   */
  SetSidebarRouters({ commit }, sidebarRouter) {
    commit('SET_SIDEBAR_ROUTERS', sidebarRouter)
  }
}

export const filterAsyncRouter = routers => {
  // 遍历后台传来的路由字符串，转换为组件对象
  return routers.filter(router => {
    if (router.component) {
      if (router.component === 'Layout') {
        // Layout组件特殊处理
        router.component = Layout
      } else {
        // 非Layout组件处理路由component
        const component = router.component
        router.component = loadView(component)
      }
    }
    if (router.children && router.children.length) {
      router.children = filterAsyncRouter(router.children)
    }
    return true
  })
}

export const loadView = view => {
  return () => import(`@/views/${view}`)
}

export default permission
